// pages/shopCar/shopCar.js
const util = require("../../utils/util.js")

Page({

  data: {
    // 默认关闭编辑弹框
    editDialogClosed: true,
    // 默认关闭授权弹框
    authDialogClosed: true,
    // 默认当前分页
    pageNumber: 1,
    // 默认分页大小
    pageSize: 10,
    // 分页数据
    goodes: [],
    // 是否还有下一页，false表示已经到最后一页了
    hasNextPage: false,
    // scrill-view竖向滚动条位置
    scrollTop: 0,
    // 默认非刷新状态
    reFreshing: false,
    // 是否全选
    isCheckAll: false,
    // 选中的商品个数
    checkCount: 0,
    // 订单总金额
    amount: 0
  },

  /**
   * 查询购物车商品信息
   */
  selectShopCarByPage: function(this_) {
    return util.requestByPost("/gdd/xcx/selectShopCarByPage/" + this_.data.pageNumber + "/" + this_.data.pageSize, {}, {
      isLogin: true,
      isPrePage: false
    }).then(res => {
      this_.data.goodes = this_.data.goodes.concat(res.list)
      this_.setData({
        reFreshing: false,
        goodes: this_.data.goodes,
        hasNextPage: res.hasNextPage
      })
    })
  },

  /**
   * 页面加载时触发。一个页面只会调用一次，可以在 onLoad 的参数中获取打开当前页面路径中的参数
   */
  onLoad: function(options) {
    // 隐藏转发按钮
    wx.hideShareMenu()
    this.onPullDownRefresh()
  },

  /**
   * 页面显示/切入前台时触发
   */
  onShow: function() {},

  /**
   * 监听用户下拉刷新动作
   */
  onPullDownRefresh: function() {
    this.setData({
      reFreshing: true,
      scrollTop: 0,
      goodes: [],
      pageNumber: 1,
      isCheckAll: false,
      checkCount: 0,
      amount: 0
    })
    this.selectShopCarByPage(this)
  },

  /**
   * scroll-view【下拉】滚动到距离顶部50px时触发
   */
  onScrollToUpper: function() {
    if (this.data.reFreshing) {
      return
    }
    wx.startPullDownRefresh()
  },

  /**
   * scroll-view【上拉】滚动到距离底部50px时触发
   */
  onScrollToLower: function() {
    if (this.data.hasNextPage) {
      this.data.pageNumber += 1
      setTimeout(() => {
        this.selectShopCarByPage(this)
      }, 300)
    } else {
      wx.showToast({
        title: '我是有底线的',
        icon: "none",
        duration: 800,
        mask: true
      })
    }
  },

  /**
   * check商品按钮
   */
  checkGoods: function(index) {
    this.data.goodes[index].isCheck = true
    this.data.checkCount += 1
    this.data.amount += this.data.goodes[index].goodsPrice * this.data.goodes[index].goodsCount
    let isCheckAll = false;
    if (this.data.checkCount == this.data.goodes.length) {
      isCheckAll = true
    }
    this.setData({
      goodes: this.data.goodes,
      amount: this.data.amount,
      isCheckAll: isCheckAll,
      checkCount: this.data.checkCount
    });
  },

  unCheckGoods: function(index) {
    this.data.goodes[index].isCheck = false
    this.data.checkCount -= 1
    this.data.amount -= this.data.goodes[index].goodsPrice * this.data.goodes[index].goodsCount
    this.setData({
      goodes: this.data.goodes,
      amount: this.data.amount,
      isCheckAll: false,
      checkCount: this.data.checkCount
    });
  },

  onCheckGoods: function(event) {
    let isCheckAll = false;
    const index = event.currentTarget.dataset.index
    const isCheck = this.data.goodes[index].isCheck ? false : true
    if (isCheck) {
      this.checkGoods(index)
    } else {
      this.unCheckGoods(index)
    }
  },

  /**
   * check全选按钮
   */
  checkAllGoods: function() {
    for (const i in this.data.goodes) {
      if (!this.data.goodes[i].isCheck) {
        this.data.goodes[i].isCheck = true
        this.data.amount += this.data.goodes[i].goodsPrice * this.data.goodes[i].goodsCount
      }
    }
    this.setData({
      goodes: this.data.goodes,
      amount: this.data.amount,
      isCheckAll: true,
      checkCount: this.data.goodes.length
    })
  },

  unCheckAllGoods: function() {
    for (const i in this.data.goodes) {
      if (this.data.goodes[i].isCheck) {
        this.data.goodes[i].isCheck = false
      }
    }
    this.setData({
      goodes: this.data.goodes,
      amount: 0,
      isCheckAll: false,
      checkCount: 0
    })
  },

  onCheckAll: function(event) {
    const isCheckAll = event.currentTarget.dataset.isCheckAll ? false : true
    if (isCheckAll) {
      this.checkAllGoods()
    } else {
      this.unCheckAllGoods()
    }

  },

  /**
   * 打开编辑弹框
   */
  onEditor: function(event) {
    const editindex = event.currentTarget.dataset.index
    this.setData({
      // 当前编辑商品的索引
      editindex: editindex,
      // 数量
      count: this.data.goodes[editindex].goodsCount,
      // 地址
      address: this.data.goodes[editindex].goodsAddress,
    })
    // 取消所有选中的商品
    this.unCheckAllGoods()
    /**
     * 判断该商品是否有附加属性
     */
    if (this.data.goodes[editindex].goodsRemark) {
      // 商品附加属性-性别
      if (this.data.goodes[editindex].goodsRemark.includes("性别")) {
        if (this.data.goodes[editindex].goodsRemark.includes("公")) {
          this.setData({
            sex: "公"
          })
        } else {
          this.setData({
            sex: "母"
          })
        }
      }
      // 商品附加属性-年龄
      if (this.data.goodes[editindex].goodsRemark.includes("年龄")) {
        if (this.data.goodes[editindex].goodsRemark.includes("成犬")) {
          this.setData({
            age: "成犬"
          })
        } else {
          this.setData({
            age: "幼犬"
          })
        }
      }
      // 商品附加属性-颜色
      if (this.data.goodes[editindex].goodsRemark.includes("颜色")) {
        if (this.data.goodes[editindex].goodsRemark.includes("白色")) {
          this.setData({
            color: "白色"
          })
        } else if (this.data.goodes[editindex].goodsRemark.includes("黑色")) {
          this.setData({
            color: "黑色"
          })
        } else if (this.data.goodes[editindex].goodsRemark.includes("棕色")) {
          this.setData({
            color: "棕色"
          })
        } else if (this.data.goodes[editindex].goodsRemark.includes("金黄色")) {
          this.setData({
            color: "金黄色"
          })
        } else if (this.data.goodes[editindex].goodsRemark.includes("褐色")) {
          this.setData({
            color: "褐色"
          })
        } else if (this.data.goodes[editindex].goodsRemark.includes("灰色")) {
          this.setData({
            color: "灰色"
          })
        }
      }
    } else {
      this.setData({
        sex: null,
        age: null,
        color: null,
        remark: null
      })
    }
    this.setData({
      editDialogClosed: false
    })
  },

  /**
   * 选择收货地址
   */
  onChooseAddress: function() {
    this.setData({
      editDialogClosed: true
    })
    const this_ = this
    util.chooseAddress(this).then(res => {
      if (typeof res === 'object') {
        this_.setData({
          address: res.provinceName + res.cityName + res.countyName + "," + res.detailInfo + "," + res.userName + "," + res.telNumber + "," + res.postalCode,
          editDialogClosed: false
        })
      }
    })
  },

  /**
   * 保存商品信息
   */
  onSave: function() {
    const this_ = this
    const count = this.data.count
    if (count === 0) {
      // 删除该数据
      util.requestByPost("/gdd/xcx/deleteShopCar", {
        id: this.data.goodes[this.data.editindex].id
      }, {
        isLogin: true,
        isPrePage: false
      }).then(res => {
        wx.showToast({
          title: "删除成功",
          icon: "success",
          mask: true,
          complete: () => {
            /**
             * 级联删除本地数据
             */
            this_.data.goodes.splice(this_.data.editindex, 1) // 删除数组中指定下表的元素
            this_.setData({
              goodes: this_.data.goodes,

            })
          }
        });
      })
    } else {
      // 保存编辑
      let goodsRemark = this.data.goodes[this.data.editindex].goodsRemark ? "性别: " + this.data.sex + ";" + "年龄: " + this.data.age + ";" + "颜色: " + this.data.color + ";" : ""
      util.requestByPost("/gdd/xcx/modifyShopCar", {
        id: this.data.goodes[this.data.editindex].id,
        goodsCount: this.data.count,
        goodsAddress: this.data.address,
        goodsRemark: goodsRemark
      }, {
        isLogin: true,
        isPrePage: false
      }).then(res => {
        wx.showToast({
          title: "修改成功",
          icon: "success",
          mask: true,
          complete: () => {
            /**
             * 级联修改本地数据
             */
            this_.data.goodes[this_.data.editindex].goodsRemark = goodsRemark
            this_.data.goodes[this_.data.editindex].goodsCount = this_.data.count
            this_.data.goodes[this_.data.editindex].goodsAddress = this_.data.address
            this_.setData({ // 回显修改后的数据
              goodes: this_.data.goodes,
              isCheckAll: false,
              checkCount: 0,
              amount: 0
            })
          }
        });
      })
    }
    // 关闭编辑弹框
    this.setData({
      editDialogClosed: true
    })
  },

  /**
   * 取消编辑
   */
  onCancel: function() {
    this.setData({
      editDialogClosed: true
    })
  },


  /**
   * 选择性别
   */
  onSelectSex: function(event) {
    this.setData({
      sex: event.currentTarget.dataset.sex
    })
  },

  /**
   * 选择年龄
   */
  onSelectAge: function(event) {
    this.setData({
      age: event.currentTarget.dataset.age
    })
  },

  /**
   * 选择颜色
   */
  onSelectColor: function(event) {
    this.setData({
      color: event.currentTarget.dataset.color
    })
  },

  /**
   * 商品数量-1
   */
  onJianCount: function(event) {
    this.data.count -= 1;
    if (this.data.count < 0) {
      this.data.count = 0;
    }
    this.setData({
      count: this.data.count
    });
  },

  /**
   * 商品数量+1
   */
  onJiaCount: function(event) {
    this.data.count += 1;
    this.setData({
      count: this.data.count
    });
  },

  /**
   * 拒绝授权
   */
  onRefuseAuth: function() {
    this.setData({
      authDialogClosed: true
    });
  },

  /**
   * 同意授权
   */
  onAcceptAuth: function() {
    this.setData({
      authDialogClosed: true
    });
  },

  /**
   * 预约
   */
  onOperation: function() {
    if (this.data.amount === 0) {
      wx.showToast({
        title: '请选择需要预约的商品',
        icon: "none",
        mask: true
      })
      return
    }
    const this_ = this
    const orderId = util.guid()
    const amount = this.data.amount
    const state = "0"
    let goodes = []
    for (const i in this.data.goodes) {
      if (this.data.goodes[i].isCheck) {
        this.data.goodes[i].id = util.guid()
        this.data.goodes[i].orderId = orderId
        goodes.push(this.data.goodes[i])
      }
    }
    util.requestByPost(`/gdd/xcx/modifyWxOrder`, {
      id: orderId,
      amount: amount,
      state: state,
      wxOrderGoods: goodes
    }, {
      isLogin: true,
      isPrePage: false
    }).then(res => {
      wx.showToast({
        title: "预约成功",
        icon: "success",
        mask: true,
        complete: () => {
          /**
           * 删除预约过的数据
           */
          this_.data.goodes = util.arraySubtracting(this_.data.goodes, goodes)
          this_.setData({
            goodes: this_.data.goodes,
            isCheckAll: false,
            checkCount: 0,
            amount: 0
          })
        }
      })
    })
  }

})